package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/19 11:50 周四
 * @description :
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return template -> {
            //1. 使用RequestContextHolder拿到老请求的请求数据
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Optional.ofNullable(requestAttributes)
                    .flatMap(r -> Optional.of(r.getRequest())).ifPresent(re -> {
                                // 同步原来的头信息 cookie
                                // 给新请求同步老请求的cookie
                                template.header("Cookie", re.getHeader("Cookie"));
                            }
                    );
        };
    }
}
